/*机构列表*/
layui.use('table', function(){
    var table = layui.table;
    table.render({
        id:"menuForm",
        elem: '#menuForm',
        url:'/sys/menu/getSysMenuData.html',
        method: 'POST', //方式
        page:{
            //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //自定义分页布局
            //,curr: 5 //设定初始在第 5 页
            groups: 1, //只显示 1 个连续页码
            first: false, //不显示首页
            last: false //不显示尾页
        },
        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        cols: [ [
            {type:'checkbox'},
            {field:'name',  title: '名称'},
            {field:'url',   title: 'URL', sort: true},
            {field:'perms', title: '权限', sort: true},
            {field:'type',  title: '层级', templet: '#statusTpl'},
            {field:'icon',  title: '图标', sort: true},
            {field:'orderNum',  title: '排序', sort: true}

        ] ]
    });
});

function search(){
    var name = $("#name").val();

    var table = layui.table;
    //table.reload("menuForm");
    table.reload("menuForm", { //此处是上文提到的 初始化标识id
        where: {
            //key: { //该写法上文已经提到
            name: name
            //}
        }
    });
}

function add() {
    var zTreeOjb = $.fn.zTree.getZTreeObj("tree");
    var selectedNodes = zTreeOjb.getSelectedNodes();
    if(selectedNodes.length!=1){
        layer.msg("请选择左侧父节点");
        return false;
    }
    var parentId = selectedNodes[0].menuId;
    var parentName =selectedNodes[0].name;
    var url = "sys/menu/add.html?parentId="+parentId+"&parentName="+parentName;


    parent.layer.open({
        type: 2,
        title: '系统菜单-新增',
        //title: false, //不显示标题
        shadeClose: true,
        skin: 'layui-layer-molv',
        shade: 0.8,
        area: ['30%', '80%'],
        content: [url,'no'], //iframe的url
        end:function () {
            //reloadTable("menuForm");
            //refreshParentNode();
            location.reload();
        }
    });
}
function edit(){
    debugger
    var table = layui.table;
    var rows = table.checkStatus('menuForm'); //test即为基础参数id对应的值
    var id = rows.data[0].menuId;
    if(rows.data.length!=1){
        layer.msg('请选择一条数据');
        return false;
    }else {
        var url = 'sys/menu/edit.html?id='+id;
        parent.layer.open({
            type: 2,
            title: '系统菜单-编辑',
            shadeClose: true,
            skin: 'layui-layer-molv',
            shade: 0.8,
            maxmin: true, //开启最大化最小化按钮
            area: ['35%', '77%'],
            content: [url,'no'], //iframe的url
            end:function () {
                //reloadTable("menuForm");
                location.reload();
            }
        });
    }
}
function del(){

    var table = layui.table;
    var rows = table.checkStatus('menuForm'); //test即为基础参数id对应的值
    var ids=[];
    if(rows.data.length<1){
        layer.msg('请选择一条数据');
        return false;
    }
    //询问框

    layer.confirm('确定要删除？', {
        btn: ['确定','取消'], //按钮
        icon: 3, title:'删除用户'
    }, function(){
        for(var i=0;i<rows.data.length;i++){
            var rowid = rows.data[i].menuId;
            ids.push(rowid);
        }
        $.ajax({
            type: "POST",
            url:"delete.html",
            data:{'ids':ids},
            traditional:true,
            cache: false,
            success:function (data) {
                if(data.code == 0){
                    layer.msg('删除成功',{time:1500},
                        function () {
                            //reloadTable("menuForm");
                            location.reload();
                        })
                }
                if("fail"==data){
                    layer.msg("删除失败",{icon:1,time:1500})
                }
            }
        })
    });
}

/**
 * @description: 树结构
 * @author 李贝留斯
 * @email sunyadongsyd@163.com
 * @date 2018/5/14 23:52
 */
var setting = {
    async:{
        enable : true,
        url : "/sys/menu/getSysMenuTreeData.html",
        autoParam : [ "sid=menuId" ],
        dataFilter:filter	//用于对 Ajax 返回数据进行预处理的函数
    },
    view: {
        expandSpeed: "",//zTree 节点展开、折叠时的动画速度，设置方法同 JQuery 动画效果中 speed 参数。
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        selectedMulti: false
    },
    edit: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true,
            idKey : "menuId",
            pIdKey : "parentId",
            rootPId : "1",
        },
        key:{
            //禁止URL跳转
            url: "xUrl",
        }
    },
    check: {
        enable: true,
        //取消关联父节点
        //setting.check.chkboxType = { "Y" : "ps", "N" : "ps" };
        chkboxType: { "Y": "ps", "N": "ps" }
    },

    callback : {
        onCheck : checked,
        onClick : zTreeOnClick,
        beforeRemove: beforeRemove,//用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
        beforeRename: beforeRename//用于捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）之后，更新节点名称数据之前的事件回调函数，并且根
    }
};

function zTreeOnClick(event, treeId, treeNode){
    var menuId = treeNode.menuId;
    var table = layui.table;
    table.reload("menuForm", { //此处是上文提到的 初始化标识id
        where: {
            //key: { //该写法上文已经提到
            menuId: menuId
            //}
        }
    });

}
//修改异步获取到的节点name属性
function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i = 0, l = childNodes.length; i < l; i++) {
        childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
    }
    return childNodes;
}

window.onload = function(){
    $.fn.zTree.init($("#tree"), setting);
    setTimeout(function(){
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getNodes();
        for (var i = 0; i < nodes.length; i++) { //设置节点展开
            treeObj.expandNode(nodes[i], true, false, true);
        }
    },500)
}

function checked(e,treeId,treeNode){
    treeNode.checkNode(node,true,true);
}

function save(){
    var treeObj=$.fn.zTree.getZTreeObj("tree");
    //var checked =  treeObj.getNodes()[0].checked;
    nodes=treeObj.getCheckedNodes(true);
    var roleid = "${roleid}";
    var sid = "";
    //v="";
    for(var i=0;i<nodes.length;i++){
        //v+=nodes[i].description + ",";
        sid += nodes[i].sid + ","
        //alert(nodes[i].sid); //获取选中节点的值
    }
    $.ajax({
        type: "POST",
        url:"/resourcerole/ztreeAdd.html",
        data:{'roleid':roleid,'sid':sid},
        traditional:true,
        cache: false,
        success:function (data) {
            if("success"==data){
                parent.layer.msg('保存成功', {shade: 0.2})
                /* layer.msg("保存成功",{icon:1,time:2000}) */
                parent.$("#grid-table").trigger("reloadGrid");
                parent.layer.close(index);
            }
        }
    })
}

//删除节点信息
function beforeRemove(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("tree");
    zTree.selectNode(treeNode);
    if (confirm("确认删除 节点 -- " + treeNode.name + " 吗？")) {
        var sid = treeNode.sid;
        $.ajax({
            url: "delete.html?sid=" + sid,
            type: "POST",
            async: false,
            success: function (res) {
                if (res = "success") {
                    alert('删除成功!');
                    window.location.reload();
                } else {
                    alert('删除失败!');
                    window.location.reload();
                }
            }
        });
    }else {
        window.location.reload();
    }
}

//修改节点信息
function beforeRename(treeId, treeNode, newName) {
    if (newName.length == 0) {
        alert("节点名称不能为空.");
        return false;
    }
    var sid = treeNode.sid;
    $.ajax({
        url: "saveOrUpdate.html?sid=" + sid + "&name=" + encodeURI(encodeURI(newName)),
        type: "POST",
        async: false,
        success: function (res) {
            if (res = "success") {
                layer.msg('修改成功', {shade: 0.2})
                window.location.reload();
            } else {
                layer.msg('修改失败', {shade: 0.2})
                window.location.reload();
            }
        }
    });
}

//添加新的节点
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click", function () {
        var zTree = $.fn.zTree.getZTreeObj("tree");
        if (confirm("确认为 " + treeNode.name + " 添加子节点吗？")) {

            // zTree.addNodes(treeNode, { id: (100 + newCount), pId: treeNode.id, name: "new node" + (newCount++) });
            var sid = treeNode.sid;
            var level = treeNode.level;
            $.ajax({
                url: "ztreeAdd.html?parentId=" + sid + "&level=" + level,
                type: "POST",
                async: false,
                success: function (res) {
                    if (res = "success") {
                        alert('添加成功!');
                        window.location.reload();
                    } else {
                        alert('添加失败!');
                        window.location.reload();
                    }
                }
            });
        }
    });
};
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_"+treeNode.tId).unbind().remove();
};
/**
 * 刷新当前选择节点的父节点
 */
function refreshParentNode() {
    var zTree = $.fn.zTree.getZTreeObj("tree"),
    type = "refresh",
    silent = false,
    nodes = zTree.getSelectedNodes();
    /*根据 zTree 的唯一标识 tId 快速获取节点 JSON 数据对象*/
    var parentNode = zTree.getNodeByTId(nodes[0].parentTId);
    /*选中指定节点*/
    zTree.selectNode(parentNode);
    zTree.reAsyncChildNodes(parentNode, type, silent);
}